/*数据缓存类
  最多支持10条缓存,可修改maxCacheCount增加限制。
  Create At 2017-12-21
*/
var cache=(function(wx){
  
  function cache(wx){
    this.wx=wx;
    this.cacheKey="article_cache";
    this.cacheList={
      count:0
    };
    this.maxCacheCount=10;
  }

  /*清除缓存*/
  cache.prototype.clear = function () {
    wx.clearStorageSync();
  }

  /*通过key值获取缓存(同步)*/
  cache.prototype.getSync=function(key){
    var cacheList = wx.getStorageSync(this.cacheKey);
    if(cacheList===undefined||cacheList===""){
      return;
    }
    return cacheList[key];
  }

  /*通过key值获取缓存（异步）*/
  cache.prototype.get=function(key,fn){
    var cacheKey=this.cacheKey;
    wx.getStorage({
      key: cacheKey,
      success:function(result){

        if(typeof(fn)==="function"){
          fn.call(this,result.data[key]);
        }
      }
    });
  }

  /*
  cache.prototype.get=function(key,fn){


  } 
  */


  /*插入缓存(异步)*/
  cache.prototype.set=function(key,data){
    var cacheList = wx.getStorageSync(this.cacheKey);
    //wx.clearStorage(this.cacheKey);
    if(cacheList==undefined||cacheList===""){
      cacheList=this.cacheList;
      console.log("缓存对象是：");
      console.log(cacheList);
    }
   
    cacheList[key]=data;
    cacheList.count++;
    if(cacheList.count>this.maxCacheCount){
      var cacheKeyList=Object.keys(cacheList);
      if(cacheKeyList!=undefined&&cacheKeyList.length>0){
        delete cacheList[cacheKeyList[0]];
        cacheList.count--;
      }
    }
    console.log("缓存插入成功");
    console.log(cacheList);
    //wx.setStorageSync(this.cacheKey, cacheList);
    wx.setStorage({
      key: this.cacheKey,
      data: cacheList,
    });

  }

  return new cache(wx);

})(wx);

module.exports.cache = cache;



